<template>
	<view class="container">
		<!-- 蓝色背景区域 -->
		<view class="blue-bg"></view>
		
		<!-- 内容区域 -->
		<view class="content">
			<!-- 顶部搜索区域 -->
			<view class="search-area">
				<view class="search-box">
					<input 
						class="search-input" 
						v-model="searchKeyword"
						placeholder="输入加油站名称" 
						placeholder-style="color: #BFBFBF"
						@confirm="handleSearch"
					/>
					<image 
						class="search-icon" 
						src="/static/搜索@2x.png" 
						mode="aspectFit"
						@click="handleSearch"
					></image>
				</view>
				<view class="mode-switch">
					<image class="mode-bg" src="/static/组 5@2x.png" mode="aspectFill"></image>
					<button class="mode-btn" @click="switchMode">
						<view class="mode-text">
							<text>{{isMapMode ? '列表' : '地图'}}</text>
							<text>模式</text>
						</view>
					</button>
				</view>
			</view>

			<!-- 油号选择 -->
			<scroll-view 
				class="oil-types" 
				scroll-x
				v-if="!isMapMode"
			>
				<view class="oil-types-content">
					<view 
						v-for="type in oilTypes" 
						:key="type"
						class="oil-type"
					>{{type}}</view>
				</view>
			</scroll-view>

			<!-- 根据模式显示不同内容 -->
			<scroll-view 
				v-if="!isMapMode"
				class="station-list"
				scroll-y
			>
				<view 
					class="station-item"
					v-for="station in stations"
					:key="station.id"
					@click="goToDetail(station)"
				>
					<view class="station-header">
						<text class="station-name">{{station.name}}</text>
						<text class="station-distance">{{station.distance}}</text>
					</view>
					<view class="discount-tags">
						<text class="discount-tag" v-for="(tag, index) in station.discounts" :key="index">{{tag}}</text>
					</view>
					<view class="station-info">
						<image class="station-image" :src="station.image" mode="aspectFill"></image>
						<view class="info-right">
							<view class="station-hours">营业时间：{{station.businessHours}}</view>
							<view class="station-price">¥{{station.price}}/升</view>
							<view class="station-address">
								{{station.address}}
								<image 
									class="nav-icon" 
									src="/static/plane@2x.png" 
									mode="aspectFit"
									@click.stop="startNavigation(station)"
								></image>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			
			<!-- 地图模式 -->
			<view v-else class="map-card">
				<map 
					id="map"
					class="map"
					:latitude="latitude"
					:longitude="longitude"
					:markers="allMarkers"
					:scale="14"
					show-location
					:show-compass="true"
					:enable-rotate="true"
					type="gcj02"
					@markertap="onMarkerTap"
				></map>
			</view>
		</view>

		<!-- 店铺信息弹窗 -->
		<view class="shop-popup" v-if="showShopInfo">
			<view class="shop-info">
				<view class="shop-basic">
					<text class="shop-name">{{currentShop.name}}</text>
					<text class="shop-address">{{currentShop.address}}</text>
					<view class="detail-btn" @click="goToDetail(currentShop)">
						<image class="detail-icon" src="/static/详情@2x.png" mode="aspectFit"></image>
						<text>门店详情 >></text>
					</view>
				</view>
				<image class="shop-image" :src="currentShop.image" mode="aspectFill"></image>
			</view>
			<!-- 立即导航按钮 -->
			<button class="nav-btn" @click="startNavigation(currentShop)">立即导航</button>
		</view>
	</view>
</template>

<script>
import amap from '@/utils/amap.js'
import locationService from '@/utils/location.js'

export default {
	data() {
		return {
			isMapMode: false,
			latitude: 35.234850,
			longitude: 113.248600,
			oilTypes: ['90#', '92#', '93#', '95#', '97#', '98#'],
			stations: [
				{
					id: 1,
					name: '中国石油加油站',
					address: '山阳区人民路与解放路交叉口',
					distance: '556m',
					price: '5.66',
					businessHours: '周一至周五',
					discounts: ['满200减20', '满500减60'],
					latitude: 35.238850,
					longitude: 113.252600,
					image: '/static/index_活动2.png'
				},
				{
					id: 2,
					name: '中国石化加油站',
					address: '山阳区太行路与新华街交叉口',
					distance: '880m',
					price: '5.58',
					businessHours: '全年无休',
					discounts: ['满300减30', '充值送券'],
					latitude: 35.237850,
					longitude: 113.251600,
					image: '/static/index_活动2.png'
				}
			],
			userLocationMarker: {
				id: 998,
				latitude: 0,
				longitude: 0,
				iconPath: '/static/椭圆 3 拷贝 2@2x.png',
				width: 18,
				height: 28,
				anchor: {x: 0.5, y: 0.5},
				zIndex: 1
			},
			userTipMarker: {
				id: 999,
				latitude: 0,
				longitude: 0,
				iconPath: '/static/矩形 5 拷贝@2x.png',
				width: 100,
				height: 35,
				anchor: {x: 0.5, y: 1},
				zIndex: 2,
				clickable: true,
				label: {
					content: '附近门店 >',
					color: '#ffffff',
					fontSize: 14,
					anchorX: -30,
					anchorY: -30,
					bgColor: 'transparent'
				}
			},
			markers: [],
			selectedShop: null,
			showShopInfo: false,
			currentShop: null,
			defaultLocation: {
				latitude: 35.234850,
				longitude: 113.248600
			},
			selectedMarkerId: null,
			searchKeyword: ''
		}
	},
	computed: {
		allMarkers() {
			return [...this.markers, this.userLocationMarker, this.userTipMarker]
		}
	},
	onLoad() {
		this.initLocation()
		this.updateStationMarkers()
	},
	methods: {
		switchMode() {
			this.isMapMode = !this.isMapMode;
			this.searchStations();
		},
		onSearchFocus() {
			// 处理搜索框聚焦事件
		},
		onSearchBlur() {
			// 处理搜索框失焦事件
		},
		updateStationMarkers() {
			this.markers = this.stations.map(station => ({
				id: station.id,
				latitude: station.latitude,
				longitude: station.longitude,
				iconPath: station.id === this.selectedMarkerId ? 
					'/static/位置 拷贝 4@2x.png' : '/static/定位2@2x.png',
				width: 24,
				height: 24,
				callout: {
					content: station.name,
					padding: 8,
					borderRadius: 4,
					display: 'BYCLICK'
				}
			}))
		},
		startNavigation(shop) {
			if (!shop || !shop.latitude || !shop.longitude) {
				uni.showToast({
					title: '店铺数据不完整',
					icon: 'none'
				});
				return;
			}
			
			uni.navigateTo({
				url: `/packagesMap/navigation/navigation?name=${shop.name}&address=${shop.address}&latitude=${shop.latitude}&longitude=${shop.longitude}`
			});
		},
		goToDetail(shop) {
			uni.navigateTo({
				url: `/packagesMap/gasStation/gasStation?id=${shop.id}&name=${shop.name}&address=${shop.address}&latitude=${shop.latitude}&longitude=${shop.longitude}&businessHours=${shop.businessHours}&price=${shop.price}&image=${shop.image}`
			})
		},
		async initLocation() {
			try {
				const location = await locationService.getCurrentLocation();
				this.updateLocation(location);
				await this.searchStations();
			} catch (err) {
				this.updateLocation(this.defaultLocation);
				uni.showToast({
					title: '定位失败，使用默认位置',
					icon: 'none'
				});
			}
		},
		updateLocation(location) {
			this.latitude = location.latitude
			this.longitude = location.longitude
			this.userLocationMarker.latitude = location.latitude
			this.userLocationMarker.longitude = location.longitude
			this.userTipMarker.latitude = location.latitude + 0.001
			this.userTipMarker.longitude = location.longitude
		},
		onMarkerTap(e) {
			const markerId = e.markerId;
			
			// 如果点击的是用户位置标记
			if (markerId === this.userTipMarker.id) {
				this.isMapMode = false;
				return;
			}
			
			// 如果点击的是加油站标记
			const station = this.stations.find(s => s.id === markerId);
			if (station) {
				this.selectedMarkerId = markerId;
				this.currentShop = station;
				this.showShopInfo = true;
				
				// 更新所有标记的图标
				this.markers = this.stations.map(s => ({
					id: s.id,
					latitude: s.latitude,
					longitude: s.longitude,
					iconPath: s.id === this.selectedMarkerId ? 
						'/static/位置 拷贝 4@2x.png' : '/static/定位2@2x.png',
					width: 24,
					height: 24,
					callout: {
						content: s.name,
						padding: 8,
						borderRadius: 4,
						display: 'BYCLICK'
					}
				}));
			}
		},
		showShopInfo() {
			if (this.stations.length > 0) {
				this.currentShop = this.stations[0]
				this.showShopInfo = true
			}
		},
		contactShop() {
			if (this.currentShop && this.currentShop.phone) {
				uni.makePhoneCall({
					phoneNumber: this.currentShop.phone
				})
			}
		},
		bookService() {
			// 处理预定服务
			uni.showToast({
				title: '预定功能开发中',
				icon: 'none'
			})
		},
		async searchStations() {
			try {
				const results = await amap.searchNearby('加油站', {
					latitude: this.latitude,
					longitude: this.longitude
				}, 5000);

				this.stations = results.detail.pois.map(poi => ({
					id: poi.id,
					name: poi.name,
					address: poi.address,
					distance: poi.distance + 'm',
					latitude: poi.latitude,
					longitude: poi.longitude,
					businessHours: poi.business_hours,
					price: poi.price,
					image: poi.image,
					discounts: poi.discounts,
					tel: poi.tel
				}));

				// 如果在地图模式下，选中第一个加油站
				if (this.isMapMode && this.stations.length > 0) {
					this.selectedMarkerId = this.stations[0].id;
					this.currentShop = this.stations[0];
					this.showShopInfo = true;
				}

				// 更新标记
				this.updateStationMarkers();
			} catch (error) {
				console.error('搜索加油站失败:', error);
			}
		},
		async handleSearch() {
			// 如果搜索关键词为空，默认搜索"加油站"
			const keyword = this.searchKeyword.trim() || '加油站';
			try {
				const results = await amap.searchNearby(keyword, {
					latitude: this.latitude,
					longitude: this.longitude
				}, 5000);

				// 更新加油站列表
				this.stations = results.detail.pois.map(poi => ({
					id: poi.id,
					name: poi.name,
					address: poi.address,
					distance: poi.distance + 'm',
					latitude: poi.latitude,
					longitude: poi.longitude,
					businessHours: poi.business_hours,
					price: poi.price,
					image: poi.image,
					discounts: poi.discounts,
					tel: poi.tel
				}));

				// 如果在地图模式下
				if (this.isMapMode && this.stations.length > 0) {
					// 选中第一个加油站
					this.selectedMarkerId = this.stations[0].id;
					this.currentShop = this.stations[0];
					this.showShopInfo = true;

					// 更新地图视野到第一个加油站
					const mapContext = uni.createMapContext('map');
					mapContext.moveToLocation({
						latitude: this.stations[0].latitude,
						longitude: this.stations[0].longitude,
						success: () => {
							// 缩放地图以显示所有标记
							if (this.stations.length > 1) {
								mapContext.includePoints({
									points: this.stations.map(station => ({
										latitude: station.latitude,
										longitude: station.longitude
									}))
								});
							}
						}
					});
				}

				// 更新地图标记
				this.markers = this.stations.map(station => ({
					id: station.id,
					latitude: station.latitude,
					longitude: station.longitude,
					iconPath: station.id === this.selectedMarkerId ? 
						'/static/位置 拷贝 4@2x.png' : '/static/定位2@2x.png',
					width: 24,
					height: 24,
					callout: {
						content: station.name,
						padding: 8,
						borderRadius: 4,
						display: 'BYCLICK'
					}
				}));

			} catch (error) {
				console.error('搜索失败:', error);
				uni.showToast({
					title: '搜索失败',
					icon: 'none'
				});
			}
		}
	},
	watch: {
		isMapMode(newVal) {
			if (!newVal) {
				this.showShopInfo = false
				this.currentShop = null
			}
		}
	}
}
</script>

<style>
.container {
	min-height: 100vh;
	background: #f5f5f5;
	position: relative;
}

.blue-bg {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	height: 360rpx;
	background-color: #2979ff;
}

.content {
	position: relative;
	z-index: 1;
	padding: 20rpx 32rpx;
}

.search-area {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 24rpx;
}

.search-box {
	flex: 1;
	position: relative;
}

.search-input {
	width: 100%;
	height: 72rpx;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 36rpx;
	padding: 0 72rpx 0 32rpx;
	font-size: 26rpx;
	box-sizing: border-box;
	color: #333;
}

.search-icon {
	position: absolute;
	right: 28rpx;
	top: 50%;
	transform: translateY(-50%);
	width: 28rpx;
	height: 28rpx;
}

.mode-switch {
	position: relative;
	width: 80rpx;
	height: 72rpx;
}

.mode-bg {
	position: absolute;
	width: 100rpx;
	height: 100rpx;
	right: -10rpx;
	top: -14rpx;
}

.mode-btn {
	position: relative;
	z-index: 1;
	background: transparent;
	color: #fff;
	font-size: 20rpx;
	height: 72rpx;
	width: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0;
	margin: 0;
	border: none;
}

.mode-btn::after {
	display: none;
}

.mode-text {
	display: flex;
	flex-direction: column;
	align-items: center;
	line-height: 1.2;
	font-size: 24rpx;
	color: #FFFFFF;
}

.oil-types {
	white-space: nowrap;
	margin: 0 -32rpx 24rpx;
	padding: 0 32rpx;
}

.oil-types-content {
	display: inline-flex;
	gap: 10rpx;
}

.oil-type {
	display: inline-block;
	font-size: 26rpx;
	color: #fff;
	padding: 8rpx 27rpx;
	border-radius: 15rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.8);
}

.station-list {
	background: #fff;
	border-radius: 20rpx;
	padding: 0;
}

.station-item {
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #eee;
}

.station-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.station-name {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.station-distance {
	font-size: 28rpx;
	color: #2979ff;
}

.discount-tags {
	display: flex;
	gap: 12rpx;
	margin-bottom: 16rpx;
}

.discount-tag {
	font-size: 22rpx;
	color: #FF6B35;
	background: rgba(255, 107, 53, 0.1);
	padding: 4rpx 12rpx;
	border-radius: 4rpx;
}

.station-info {
	display: flex;
	gap: 20rpx;
}

.station-image {
	width: 160rpx;
	height: 120rpx;
	border-radius: 8rpx;
}

.info-right {
	flex: 1;
}

.station-hours {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 8rpx;
}

.station-price {
	font-size: 28rpx;
	color: #FF6B35;
	margin-bottom: 8rpx;
}

.station-address {
	font-size: 24rpx;
	color: #666;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.nav-icon {
	width: 24rpx;
	height: 24rpx;
}

.content {
	position: relative;
	z-index: 1;
	padding: 32rpx;
	height: 100%;
}

.map-card {
	width: 100%;
	height: calc(100vh - 200rpx);
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	position: relative;
}

.map {
	width: 100%;
	height: 100%;
}

.shop-popup {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	z-index: 100;
	padding: 32rpx;
}

.shop-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 32rpx;
}

.shop-basic {
	flex: 1;
	padding-right: 24rpx;
}

.shop-name {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 12rpx;
	display: block;
}

.shop-address {
	font-size: 26rpx;
	color: #666;
}

.shop-image {
	width: 160rpx;
	height: 120rpx;
	border-radius: 8rpx;
}

.nav-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	background: #2979ff;
	color: #fff;
	font-size: 32rpx;
	border-radius: 44rpx;
	text-align: center;
	border: none;
}

.detail-btn {
	display: flex;
	align-items: center;
	margin-top: 12rpx;
}

.detail-icon {
	width: 28rpx;
	height: 28rpx;
	margin-right: 8rpx;
}

.detail-btn text {
	font-size: 24rpx;
	color: #2979ff;
}

.nearby-shops-btn {
	display: none;
}
</style>
